<?php

/* * 
 * 资讯
 */
namespace Common\Model;
use Think\Model;
class BaseModel extends Model {

    protected $currentTableName;
    protected $currentKeyPrefix;

    function _initialize() {
        parent::_initialize();
        $this->currentTableName = getModelValidName(get_class($this));
        $this->currentKeyPrefix = mapTablePrefixName($this->currentTableName);
    }

    /**
     * 根据map查表
     * @param $map
     * @return mixed
     */
    public function queryByMap($map) {
        $info = $this->where($map)->find();
        return $info;
    }

    /**
     * 更新某一实体类
     * @param $obj
     */
    public function updateInfo($obj) {

        $this->where(array($this
            ->currentKeyPrefix=>$obj[$this->currentKeyPrefix]))->save($obj);

    }

    /**
     * 根据主键ID删除记录
     * @param $id
     */
    public function deleteById($id) {

        $sql = "delete from " . C("DB_PREFIX") . $this->currentTableName
                . " where " . $this->currentKeyPrefix . " = " . $id;
        M()->execute($sql);

    }

    /**
     * 根据主键ID查询记录
     * @param $id
     * @return mixed
     */
    public function queryById($id) {

        $sql = "select * from " . C("DB_PREFIX") . $this->currentTableName
            . " where " . $this->currentKeyPrefix . " = " . $id;
        $data = M()->query($sql);

        return $data[0];

    }

    /**
     * 根据ID新增或修改记录
     * @param $id
     * @return bool
     */
    public function saveOrUpdate($id) {

        if(!$this->create()) {
            return false;
        } else {
            if(isNullOrEmpty($id)) {
                $this->add();
            } else {
                $this->save();
            }
            return true;
        }

    }

    /**
     * 根据键值对、分页查询单表列表
     * @param $map
     * @param $page
     * @return mixed
     */
    public function queryForList($page=null, $map=null) {

        $sql = "select * from " . C("DB_PREFIX") . $this->currentTableName
            . " where " . getWhereSqlByMap($map)
            . " order by " . $this->currentKeyPrefix . " desc";

        if(!isNullOrEmpty($page)) {
            $sql .= " limit " . $page->firstRow . ',' . $page->listRows;
        }

        $data = M()->query($sql);

        return $data;

    }

    public function getListCount($map = null) {

        $sql = "select count(1) as counts from " . C("DB_PREFIX") . $this->currentTableName
            . " where " . getWhereSqlByMap($map);

        $data = M()->query($sql);

        return $data[0]['counts'];

    }

}

